package com.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.dao.ProductDao;
import com.boot.entity.Product;
import com.boot.exception.ServiceException;
import com.boot.service.ProductService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 商品表(Product)表服务实现类
 *
 * @author makejava
 * @since 2023-07-20 18:48:26
 */
@Service("productService")
public class ProductServiceImpl extends ServiceImpl<ProductDao, Product> implements ProductService {

    @Override
    public List<Product> queryOneOrAllProduct(Integer pid) {
        // 查询上架商品
        return super.query().eq("status", 1).eq(pid != null, "id", pid).list();
    }

    /**
     * 管理员新增商品
     *
     * @param p
     * @return
     */
    @Override
    public Boolean insertProduct(Product p) {

        if (p.getInventory() > 0) p.setStatus(1);
        else p.setStatus(-1);
        return this.save(p);
    }

    /**
     * 根据商品id更改商品上架状态
     *
     * @param pid
     * @param status
     * @return
     */
    @Override
    public Boolean updateStatus(Integer pid, Integer status) {
        Product product = this.query().eq("id", pid).one();
        if (Objects.equals(product.getStatus(), status)) {
            if (status == 1) throw new ServiceException(401, "无需重复上架");
            if (status == -1) throw new ServiceException(401, "无需重复下架");
        }
        UpdateWrapper<Product> updateWrapper = new UpdateWrapper<>();
        String sql = "status=" + status;
        boolean b = this.update(updateWrapper.eq("id", pid).setSql(sql));
        System.out.println(b);
        return b;
    }
}

